package br.com.werp.regras.geral.visao.taglib;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.beanutils.BeanUtils;

import br.com.werp.regras.geral.Debuger;
import br.com.werp.regras.geral.GerenciadorErros;
import br.com.werp.regras.geral.util.XmlResponseGenerator;


public class AjaxResponseTag extends MasterTag {
    public static final long serialVersionUID = 4176532965741291294L;
    public final static String AJAX_RESPONSE = "ajax_respose";
    public final static String FORM_AJAX_RESPONSE = "form_ajax_respose";

    public void otherDoStartTagOperations() {
        JspWriter out = pageContext.getOut();
        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        Object object = request.getAttribute(AJAX_RESPONSE);

        try {
            if (object == null) {
                object = request.getAttribute(FORM_AJAX_RESPONSE);
                object = BeanUtils.describe(object);

                Map mapa = (Map) object;
                mapa.remove("class");
                mapa.remove("servletWrapper");
            }

            String xml = XmlResponseGenerator.parseObj2Xml(object).trim();

            /*
             * Removendo a parte <?xml version="1.0" encoding="UTF-8"?>
             * pois ja eh gerado no ajax jsp em
             * <%@ page contentType="text/xml"
             */
            String[] strArray = xml.split("<root");

            if (strArray.length > 1) {
                xml = "<root" + strArray[1];
            }

            Debuger.debugar(xml, getClass());

            out.write(xml);
        } catch (Exception e) {
            GerenciadorErros.logarErro(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(System.getProperties());
    }
}
